package com.simba.server.framedecoder.decoders;

import com.simba.common.frameserver.FrameChannelManager;
import com.simba.common.utils.StringUtil;
import com.simba.server.components.*;
import com.simba.server.components.data.SortInfo;
import com.simba.server.components.data.SorterInfo;
import org.apache.log4j.Logger;
import org.jboss.netty.channel.Channel;
import com.simba.common.decoder.Decoder;
import com.simba.common.log.LogUtil;
import com.simba.common.utils.FrameUtils;

import java.sql.Timestamp;

public class PacketOnDecoder implements Decoder
{
	private static class PacketOnDecoderHolder
	{
		private static final PacketOnDecoder INSTANCE = new PacketOnDecoder();
	}

	public final static String NAME = "PacketOn";
	protected final static Logger logger = Logger.getLogger(PacketOnDecoder.class);

	private static final int SORTER_NUM_POSITION = 3;
	private static final int STR_CONTENT_BEGIN_POSITION = 5;
	private static final int STR_CONTENT_END_POSITION = 2;
	private static final int WEIGHT_POSITION = 0;
	private static final int WEIGHT_LENGTH = 5;
	private static final int PLC_LEN = 17;
	private static final int EDGE_LENGTH = 4;
//	西班牙 胖哥的体积都是7位
//	private static final int VOLUME_LENGTH = 7;
//	美国云途 杰哥的体积是12位
	private static final int VOLUME_LENGTH = 12;

	public static PacketOnDecoder getDecoderInstance()
	{
		return PacketOnDecoderHolder.INSTANCE;
	}

	private PacketOnDecoder()
	{

	}

	@Override
	public void doDecode(Channel channel, Object message)
	{
		try
		{
			ChannelsManager.getInstance().updateClient(channel);

			byte[] content = (byte[]) message;
			LogUtil.LogInfo(logger,"收到plc来的上件报文"+ StringUtil.byteToHexString(content));
			int sorterID = FrameUtils.getInstance().getUnsignedShortBigEndian(SORTER_NUM_POSITION, content);
			SorterInfo wheelSorterInfo = SorterManager.getInstance().getWheelSorterByID(String.valueOf(sorterID));
			if (wheelSorterInfo == null)
			{
				LogUtil.LogError(logger, "[WheelPacketOnDecoder] Sorter not found! Sorter ID:" + sorterID);
				return;
			}

			byte[] plcIdBuffer = new byte[PLC_LEN];
			System.arraycopy(content, STR_CONTENT_BEGIN_POSITION + WEIGHT_LENGTH, plcIdBuffer, 0, PLC_LEN);

			int contentLen = content.length;
			String strContent = new String(content, STR_CONTENT_BEGIN_POSITION, contentLen - STR_CONTENT_END_POSITION - STR_CONTENT_BEGIN_POSITION, "UTF-8");


			int weightLen = WEIGHT_LENGTH;
			int weightPosition = WEIGHT_POSITION;

			String weight = strContent.substring(weightPosition, weightLen);


			int handPosition = weightPosition + weightLen;

			String plcId = strContent.substring(handPosition, handPosition + PLC_LEN);
			handPosition = handPosition + PLC_LEN;

			String packageLength = strContent.substring(handPosition, handPosition + EDGE_LENGTH);
			handPosition = handPosition + EDGE_LENGTH;

			String packageWidth = strContent.substring(handPosition, handPosition + EDGE_LENGTH);
			handPosition = handPosition + EDGE_LENGTH;

			String packageHeight = strContent.substring(handPosition, handPosition + EDGE_LENGTH);
			handPosition = handPosition + EDGE_LENGTH;

			String packageVolume = strContent.substring(handPosition, handPosition + VOLUME_LENGTH);
			handPosition = handPosition + VOLUME_LENGTH;



			SortInfo wheelSortInfo = SortInfoManager.getInstance().createSortInfo();
			wheelSortInfo.setPlcId(plcId);
			wheelSortInfo.setPlcLdBuf(plcIdBuffer);
			wheelSortInfo.setSorterId(String.valueOf(sorterID));
			wheelSortInfo.setLength(packageLength);
			wheelSortInfo.setWidth(packageWidth);
			wheelSortInfo.setHeight(packageHeight);
			wheelSortInfo.setVolume(packageVolume);
			wheelSortInfo.setWeight(weight);

			String strBarcodeNumber = strContent.substring(handPosition, handPosition + 2);
			int barcodeNumber = Integer.parseInt(strBarcodeNumber);
			handPosition = handPosition + 2;

			for (int i = 0; i < barcodeNumber; i++)
			{
				handPosition = handPosition + 2;
				String strBarcodeLen = strContent.substring(handPosition, handPosition + 3);
				handPosition = handPosition + 3;

				int barcodeLen = Integer.parseInt(strBarcodeLen);

				String barcode = strContent.substring(handPosition, handPosition + barcodeLen);

				wheelSortInfo.setBarcode(barcode);
				wheelSortInfo.getBarcodeList().add(barcode);

				handPosition = handPosition + barcodeLen;
			}
			LogUtil.LogInfo(logger,"收到plc来的上件报文,条码是"+ wheelSortInfo.getBarcodeList()+"重量是"+weight+"报文"+StringUtil.byteToHexString(content));

			Timestamp packetOnTime = SortProtocolCreator.getInstance().createCurrentTimeStamp();
			wheelSortInfo.setTimestampPacketOn(packetOnTime);

			SortControllerManager.getInstance().onPacketOnMessage(wheelSortInfo);

			this.sendToPlc(channel, wheelSorterInfo, wheelSortInfo);
		}
		catch (Exception ex)
		{
			LogUtil.LogError(PacketOnDecoder.logger,
					"PacketOn Decoder Error : exception info : " + ex.getMessage());
		}
	}

	@Override
	public String getName()
	{
		return PacketOnDecoder.NAME;
	}

	private void sendToPlc(Channel channel, SorterInfo wheelSorterInfo, SortInfo wheelSortInfo)
	{
		LogUtil.LogInfo(logger,"发往plc落格"+wheelSortInfo.getSlotsList()+"条码是 "+wheelSortInfo.getBarcodeList());
		byte[] sortResultBuffer = SortProtocolCreator.getInstance().createSortResultBuffer(wheelSorterInfo, wheelSortInfo);
		FrameChannelManager.getInstance().commitResponse(channel, sortResultBuffer, false);
	}
}
